//
//  OBMomentItemViewModel.m
//  WeChat
//
//  Created by 黄柳姣 on 2018/5/2.
//  Copyright © 2018年 obally. All rights reserved.
//

#import "OBMomentItemViewModel.h"
#import <YYKit/NSAttributedString+YYText.h>
#import "NSMutableAttributedString+OBMoment.h"

@interface OBMomentItemViewModel ()
/// 展开全文cmd
@property (nonatomic, readwrite, strong) RACCommand *expandOperationCmd;
/// 点赞+评论列表 （设计为 可变数组 后期需要添加东西）
@property (nonatomic, readwrite, strong) NSMutableArray *dataSource;
@end
@implementation OBMomentItemViewModel
- (instancetype)initWithMoment:(OBMomentModel *)moment
{
    if (self = [super init]) {
        //内容高度
        CGFloat limitWidth = OBMomentCommentViewWidth();
        //单行文字container
        YYTextContainer *singleRowContainer = [YYTextContainer containerWithSize:YYTextContainerMaxSize];
        singleRowContainer.maximumNumberOfRows = 1;
        /// 高亮背景
        YYTextBorder *border = [YYTextBorder new];
        border.cornerRadius = 0;
        border.insets = UIEdgeInsetsMake(0, -1, 0, -1);
        border.fillColor = OBMomentTextHighlightBackgroundColor;
        
        //模型属性
        self.moment = moment;
        //昵称
        if (OBStringIsNotEmpty(moment.sender.nick)) {
            ///富文本
            NSMutableAttributedString *nickNameStr = [[NSMutableAttributedString alloc]initWithString:moment.sender.nick];
            nickNameStr.font = OBMomentScreenNameFont;
            nickNameStr.color = OBMomentScreenNameTextColor;
            nickNameStr.lineBreakMode = NSLineBreakByWordWrapping;
            nickNameStr.alignment = NSTextAlignmentLeft;
            //设置高亮
            YYTextHighlight *highLight = [YYTextHighlight new];
            [highLight setBackgroundBorder:border];
            //布局实现
            YYTextContainer *nickNameContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
            nickNameContainer.maximumNumberOfRows = 1;
            YYTextLayout *nickNameLayout = [YYTextLayout layoutWithContainer:nickNameContainer text:nickNameStr.copy];
            self.nickNameLableLayout = nickNameLayout;
            
        }
        ///正文有值
        if (OBStringIsNotEmpty(moment.content)) {
            NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.content];
            textAttr.font = OBMomentContentFont;
            textAttr.color = OBMomentContentTextColor;
            textAttr.lineBreakMode = NSLineBreakByCharWrapping;
            textAttr.alignment = NSTextAlignmentLeft;
            /// 去正则匹配
            [textAttr ob_regexContentWithWithEmojiImageFontSize:15];
            
            YYTextContainer *contentLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
            contentLableContainer.maximumNumberOfRows = 0;
            YYTextLayout *contentLableLayout = [YYTextLayout layoutWithContainer:contentLableContainer text:textAttr.copy];
            self.contentLableLayout = contentLableLayout;
        }
        ///配图
        self.picInfos = [moment.images.rac_sequence map:^OBMomentPhotoItemViewModel *(OBImageModel *image) {
            OBMomentPhotoItemViewModel *viewModel = [[OBMomentPhotoItemViewModel alloc]initWithPicture:image];
            return viewModel;
        }].array;
        
        ///评论
        if (moment.comments.count > 0) {
            [self.dataSource addObjectsFromArray:[moment.comments.rac_sequence map:^OBMomentCommentItemViewModel *(OBCommentModel *commentModel) {
                OBMomentCommentItemViewModel *viewModel = [[OBMomentCommentItemViewModel alloc]initWithComment:commentModel];
                return viewModel;
            }].array];
        }
        
        /// ----------- 尺寸属性 -----------
        /// 头像
        CGFloat avatarViewX = OBMomentContentLeftOrRightInset;
        CGFloat avatarViewY = OBMomentContentTopInset;
        CGFloat avatarViewW = OBMomentAvatarWH;
        CGFloat avatarViewH = OBMomentAvatarWH;
        self.avatarViewFrame = CGRectMake(avatarViewX, avatarViewY, avatarViewW, avatarViewH);
        
        /// 昵称
        CGFloat screenNameLableX = CGRectGetMaxX(self.avatarViewFrame)+OBMomentContentInnerMargin;
        CGFloat screenNameLableY = avatarViewY;
        CGFloat screenNameLableW = self.nickNameLableLayout.textBoundingSize.width;
        CGFloat screenNameLableH = self.nickNameLableLayout.textBoundingSize.height;
        self.screenNameLableFrame = CGRectMake(screenNameLableX, screenNameLableY, screenNameLableW, screenNameLableH);
        
        /// 由于要点击 全文/展开 更新子控件的尺寸 , 故抽取出来
        [self _updateSubviewsFrameWithExpand:self.expand];
        ////  ---------- 初始化单条说说的上的所有事件处理 ------------
        [self initialize];
    }
    return self;
}
#pragma mark - 初始化所有后面事件将要执行的命令
- (void)initialize
{
    @weakify(self);
    self.expandOperationCmd = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(NSNumber *input) {
        @strongify(self);
        self.expand = !self.expand;
        ///更新所有布局
        [self _updateSubviewsFrameWithExpand:self.expand];
        /// 回调控制器
        [self.reloadSectionSubject sendNext:input];
        return [RACSignal empty];
    }];
}
/**
 更新内部控件尺寸模型 （点击全文or收起）
 @param expand 全文/收起
 */
- (void)_updateSubviewsFrameWithExpand:(BOOL)expand
{
    self.expand = expand;
    CGFloat limitWidth = OBMomentCommentViewWidth();
    ///正文
    CGFloat contentLableX = self.screenNameLableFrame.origin.x;
    /// -4 修正间距
    CGFloat contentLableY = CGRectGetMaxY(self.screenNameLableFrame)+OBMomentContentInnerMargin-4;
    /// 需要计算正文的size default 正文为空
    CGSize contentLableSize = CGSizeZero;
    ///全文/收起按钮
    CGFloat expandBtnX = contentLableX;
    CGFloat expandBtnY = contentLableY;
    CGFloat expandBtnW = OBMomentExpandButtonWidth;
    CGFloat expandBtnH = 0;
    
    ///正文 分情况显示
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
    YYTextLayout *layout = nil;
    if (OBStringIsNotEmpty(self.moment.content)) {
        contentLableSize = self.contentLableLayout.textBoundingSize;
        //计算尺寸  超过最大行数
        if (self.contentLableLayout.rowCount > OBMomentContentTextExpandCriticalRow) {
            ///重新计算
            if (!expand) {
                /// 点击收起 ----显示全文
                container.maximumNumberOfRows = OBMomentContentTextExpandCriticalRow;
                layout = [YYTextLayout layoutWithContainer:container text:self.contentLableLayout.text];
                contentLableSize = layout.textBoundingSize;
            }
            expandBtnH = OBMomentExpandButtonHeight;
        }
        /// 全文/收起Y
        expandBtnY = contentLableY + contentLableSize.height +OBMomentContentInnerMargin;
    }
    /// 正文
    self.contentLableFrame = CGRectMake(contentLableX, contentLableY, contentLableSize.width, contentLableSize.height);
    
    /// 全文/收起
    self.expandBtnFrame = CGRectMake(expandBtnX, expandBtnY, expandBtnW, expandBtnH);
    /// 配图View
    CGFloat pictureViewX = contentLableX;
    CGFloat pictureViewTopMargin = (expandBtnH > 0)?OBMomentContentInnerMargin:0;
    CGFloat pictureViewY = CGRectGetMaxY(self.expandBtnFrame) + pictureViewTopMargin;
    CGSize  pictureViewSize = [self _pictureViewSizeWithPhotosCount:self.moment.images.count];
    self.photosViewFrame = (CGRect){{pictureViewX , pictureViewY},pictureViewSize};
    /// 整个header的高度
    self.height = CGRectGetMaxY(self.photosViewFrame);
    [self updateUpArrow];
}
- (void)updateUpArrow{
    [self _updateUpArrowViewFrameForOperationMoreChanged];
}
/// pictureView的整体size
- (CGSize)_pictureViewSizeWithPhotosCount:(NSUInteger)photosCount
{
    // 0张图 CGSizeZero
    if (photosCount==0) return CGSizeZero;
    CGFloat pictureViewItemWH = OBMomentPhotosViewItemWidth();
    /// 考虑一张图片等比显示的情况
    if (photosCount == 1) {
        CGSize picSize = CGSizeZero;
        CGFloat maxWidth = OBMomentPhotosViewSingleItemMaxWidth();
        CGFloat maxHeight = OBMomentPhotosViewSingleItemMaxHeight;
        /// 固定方形
        picSize = CGSizeMake(maxWidth, maxWidth);
        return picSize;
    }
     /// 大于1的情况 统统显示 九宫格样式
    NSUInteger maxCols = OBMomentMaxCols(photosCount);
    //总列数
    NSUInteger totalCols = photosCount >= maxCols ? maxCols : photosCount;
    // 总行数
    NSUInteger totalRows = (photosCount + maxCols - 1) / maxCols;
    // 计算尺寸
    CGFloat photosW = totalCols * pictureViewItemWH + (totalCols - 1) * OBMomentPhotosViewItemInnerMargin;
    CGFloat photosH = totalRows * pictureViewItemWH + (totalRows - 1) * OBMomentPhotosViewItemInnerMargin;
    return CGSizeMake(photosW, photosH);
}
/// 由于更多按钮的事件生效（PS：点赞成功/失败 Or 评论成功/失败）都会导致headerView的高度changeed
- (void)_updateUpArrowViewFrameForOperationMoreChanged
{
    BOOL isAllowShowUpArrowView = self.moment.comments.count>0;
    
    CGFloat upArrowViewX = self.screenNameLableFrame.origin.x;
    /// -5是为了适配
    CGFloat upArrowViewTopMargin = isAllowShowUpArrowView?(OBMomentContentInnerMargin-5):0;
    CGFloat upArrowViewY = CGRectGetMaxY(self.photosViewFrame)+upArrowViewTopMargin;
    CGFloat upArrowViewW = OBMomentUpArrowViewWidth;
    CGFloat upArrowViewH = isAllowShowUpArrowView?OBMomentUpArrowViewHeight:0;
    self.upArrowViewFrame = CGRectMake(upArrowViewX, upArrowViewY, upArrowViewW, upArrowViewH);
    
    /// 整个header的高度
    self.height = CGRectGetMaxY(self.upArrowViewFrame);
    //既没有文字 也没有图片
    if (self.moment.content.length == 0 && self.moment.images.count == 0) {
         self.height = CGRectGetMaxY(self.avatarViewFrame) + OBMomentContentInnerMargin;
    }
   
}
#pragma mark - Getter & Setter
- (NSMutableArray *)dataSource{
    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}
- (void)setAttributedTapCommand:(RACCommand *)attributedTapCommand{
    _attributedTapCommand = attributedTapCommand;
    
    /// 遍历数据源 dataSource
    for (OBMomentCommentItemViewModel *itemViewModel in self.dataSource) {
        itemViewModel.attributedTapCommand = attributedTapCommand;
    }
}
@end
